package com.byzk.p2p.admin.borrow.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.borrow.dao.ChangeDao;
import com.byzk.p2p.admin.borrow.dao.TenderDao;
import com.byzk.p2p.admin.borrow.dto.Change;
import com.byzk.p2p.admin.borrow.dto.ChangeRecord;
import com.byzk.p2p.admin.borrow.dto.UserTender;
import com.byzk.p2p.admin.borrow.vo.AllowChangeVo;
import com.byzk.p2p.admin.borrow.vo.ChangeAwaitVo;
import com.byzk.p2p.admin.borrow.vo.ChangeVo;
import com.byzk.p2p.admin.borrow.vo.MyChangeVo;
import com.byzk.p2p.admin.money.dao.BorrowPaymentDetailDao;
import com.byzk.p2p.admin.money.dao.FundRecordDao;
import com.byzk.p2p.admin.money.dto.BorrowPaymentDetail;
import com.byzk.p2p.admin.money.dto.FundRecord;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.vo.BorrowPaymentDetailVo;
import com.byzk.p2p.admin.money.vo.SumWithdrawVo;
import com.byzk.p2p.admin.money.vo.WithdrawRecordVo;
import com.byzk.p2p.admin.user.dao.UserAccountDao;
import com.byzk.p2p.admin.user.dao.UserDao;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;

@Service
public class ChangeService {

	@Autowired
	private ChangeDao changeDao;
	@Autowired
	private UserAccountDao userAccountDao;
	@Autowired
	private TenderDao tenderDao;
	@Autowired
	private FundRecordDao recordDao;
	@Autowired
	private UserDao userDao ;
	@Autowired
	private BorrowPaymentDetailDao borrowPaymentDetailDao ;
	
	public PageInfo<ChangeVo> listChange(int index,int limit,ChangeVo changeVo){
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("start", (index-1)*limit);
		queryMap.put("limit", limit);
		queryMap.put("status", changeVo.getStatus());
		queryMap.put("period", changeVo.getPeriod());
		if(changeVo!=null &&changeVo.getChangeMoney()!=null){
		if(changeVo.getChangeMoney() == 1){
			queryMap.put("amountBegin", 1000);
		}else if(changeVo.getChangeMoney()==2){
			queryMap.put("amountBegin", 1000);
			queryMap.put("amountEnd", 5000);
		}else if(changeVo.getChangeMoney()==3){
			queryMap.put("amountBegin", 5000);
			queryMap.put("amountEnd", 10000);
		}else if(changeVo.getChangeMoney()==4){
			queryMap.put("amountBegin", 10000);
			queryMap.put("amountEnd", 50000);
		}else if(changeVo.getChangeMoney()==5){
			queryMap.put("amountBegin", 50000);
			queryMap.put("amountEnd", 10000);
		}else if(changeVo.getChangeMoney()==6){
			queryMap.put("amountEnd", 100000);
		}
		}
		queryMap.put("contantPercentBegin", changeVo.getContantPercentBegin());
		queryMap.put("contantPercentEnd", changeVo.getContantPercentEnd());
		queryMap.put("exceptCancelChange", changeVo.getExceptCancelChange());
		int count=changeDao.countChange(queryMap);
		List<ChangeVo> listChange=changeDao.listChange(queryMap);
		List<ChangeVo> listChange1 = new ArrayList<ChangeVo>();
		if (listChange != null && listChange.size() > 0) {
			for (ChangeVo item : listChange) {
				if (item.getChangeUserId() != null) {
					User user = userDao.getById(item.getChangeUserId());
					item.setChangeUsername(user.getUsername());
				}
				listChange1.add(item);
			}
		}
		PageInfo<ChangeVo> page=new PageInfo<ChangeVo>(count, index , limit);
		page.setPageList(listChange1);
		return page;
	}
	
	public Integer saveOrUpdateChange(Change change){
		if(change.getId()==null){
			return changeDao.insert(change);
		}else{
			return changeDao.update(change);
		}
	}
	
	public Integer saveOrUpdateRecord(ChangeRecord record){
		if(record.getId()==null){
			return changeDao.insertRecord(record);
		}else{
			return changeDao.updateRecord(record);
		}
	}
	
	/**
	 * 根据债权id获取竞拍记录
	 * @param changeId
	 * @return
	 */
	public List<ChangeRecord> listByChangeId(Integer changeId){
		return changeDao.selectByChangeId(changeId);
	}
	
	
	/**
	 * 我承接的债权
	 * @param userId 承接者的用户id
	 * @return
	 */
	public PageInfo<MyChangeVo> listByChangeUserId(Change change){
		int count = changeDao.changeCount(change);
		List<MyChangeVo> voList= changeDao.listByChangeUserId(change);
		PageInfo<MyChangeVo> page= new PageInfo<MyChangeVo>(count,change.getIndex(),change.getLimit());
		page.setPageList(voList);
		return page;
	}
	
	public ChangeVo getChange(Integer changeId){
		return changeDao.selectById(changeId);
	}
	
	/**
	 * 根据借款标id和投资id获取债权
	 * @param borrowId 借款标id
	 * @param tenderId 投资id
	 * @return
	 */
	public Change getChangeByTenderIdAndBorrowId(Integer borrowId,Integer tenderId){
		return changeDao.getChangeByTenderIdAndBorrowId(borrowId, tenderId);
	}
	
	public Change getById(Integer id){
		return changeDao.getById(id);
	}
	
	public List<ChangeVo> top3ChangeList(){
		return changeDao.top3ChangeList();
	}
	
	public List<BorrowPaymentDetailVo> getChangePaymentDetailRecord(Integer borrowId,Integer userId,Integer changeId){
		return changeDao.getChangePaymentDetailRecord(borrowId,userId,changeId);
	}
	
	public Double getChangePaymentDetailRecordMoney(Integer borrowId,Integer userId,Integer changeId){
		return changeDao.getChangePaymentDetailRecordMoney(borrowId,userId,changeId);
	}
	
	/**
	 * 
	 * @param userId  购买用户id
	 * @param changeId
	 * @return
	 */
	public Integer buyChange(Integer userId,Integer changeId){
		Change change = changeDao.getById(changeId);
		//成交价格
		double money=tenderDao.sumAwaitByNotChange(change.getTenderId());
		//转让期数
		Integer period=tenderDao.countAwaitByNotChange(change.getTenderId());
		change.setMoney(money);
		change.setPeriod(period);
		change.setStatus("Y");
		change.setUpdateTime(new Date());
		change.setChangeUserId(userId);
		changeDao.update(change);
		
		ChangeRecord record=new ChangeRecord();
		record.setChangeId(change.getId());
		record.setAmount(change.getMin());
		record.setCreateTime(new Date());
		record.setUserId(userId);
		record.setOriginalUserId(change.getUserId());
		
		changeDao.insertRecord(record);
		
		changeDao.updateChangeBorrowPaymentDetail(change.getUserId(),change.getBorrowId(),change.getTenderId());
		
		/**
		 * 购买用户
		 */
		UserAccount account1=userAccountDao.getByUserId(userId);
		ChangeAwaitVo await=tenderDao.sumChangeAwait(userId,changeId);
		account1.setBalance(account1.getBalance()-change.getMin());
		account1.setTotalAmount(account1.getTotalAmount()-change.getMin()+await.getPaymentTotal());
		account1.setTotalExpenses(account1.getTotalExpenses()+change.getMin());
		userAccountDao.update(account1);
		
		FundRecord fundRecord1=new FundRecord();
		fundRecord1.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
		fundRecord1.setCreateTime(new Date());
		fundRecord1.setExpend(change.getMin());
		fundRecord1.setUserId(userId);
		fundRecord1.setIncome(0d);
		fundRecord1.setTerminal("PC");
		fundRecord1.setRemark("购买债权");
		fundRecord1.setType(FundRecordType.Type.BUY.index);
		fundRecord1.setFreezen(account1.getFreezen());
		fundRecord1.setBalance(account1.getBalance());
		recordDao.insert(fundRecord1);
		
		/**
		 * 转让用户
		 */
		UserAccount account=userAccountDao.getByUserId(change.getUserId());
		account.setBalance(account.getBalance()+change.getMin());
		account.setTotalAmount(account.getTotalAmount()-await.getPaymentTotal()+change.getMin());
		account.setTotalIncome(account.getTotalIncome()+change.getMin());
		account.setTotalExpenses(account.getTotalExpenses());
		userAccountDao.update(account);
		
		FundRecord fundRecord=new FundRecord();
		fundRecord.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
		fundRecord.setCreateTime(new Date());
		fundRecord.setExpend(0d);
		fundRecord.setUserId(change.getUserId());
		fundRecord.setIncome(change.getMin());
		fundRecord.setTerminal("PC");
		fundRecord.setRemark("出售债权");
		fundRecord.setType(FundRecordType.Type.CHANGE.index);
		fundRecord.setFreezen(account.getFreezen());
		fundRecord.setBalance(account.getBalance());
		recordDao.insert(fundRecord);
		
		updateTenderUser(change);
		
		
		
//		FundRecord fundRecord3=new FundRecord();
//		fundRecord3.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
//		fundRecord3.setCreateTime(new Date());
//		fundRecord3.setExpend(change.getPoundage());
//		fundRecord3.setUserId(change.getUserId());
//		fundRecord3.setIncome(0d);
//		fundRecord3.setTerminal("PC");
//		fundRecord3.setRemark("债权转让手续费");
//		fundRecord3.setType(FundRecordType.Type.CHANGE_POUNDAGE.index);
//		fundRecord3.setFreezen(account.getFreezen());
//		fundRecord3.setBalance(account.getBalance());
//		recordDao.insert(fundRecord3);
		return 1;
	}
	
	public Integer delete(Integer id){
		return changeDao.delete(id);
	}

	public Change getChangeByTenderIdAndBorrowIdAndUserId(Integer borrowId, Integer userId, Integer tenderId) {
		return changeDao.getChangeByTenderIdAndBorrowIdAndUserId(borrowId, userId, tenderId);
	}

	/**
	 * 根据标id和投资id查询该标是否已二次转让
	 * @param borrowId
	 * @param tenderId
	 * @return
	 */
	public Change changeByTenderIdAndBorrowId(Integer borrowId,Integer tenderId){
		return changeDao.changeByTenderIdAndBorrowId(borrowId, tenderId);
	}
	
	
	public Change getChangeByTenderIdAndBorrowIdAndChangeUserId(Integer borrowId, Integer changeUserId, Integer tenderId) {
		return changeDao.getChangeByTenderIdAndBorrowIdAndChangeUserId(borrowId, changeUserId, tenderId);
	}
	
	/**
	 * 
	* <p>Description:更新投资用的的待收 </p>
	* <p>Company:xbd </p>
	* @author:lilei
	* @date:2016年10月31日上午11:28:48
	 */
	public void updateTenderUser(Change change) {
		UserTender tender = tenderDao.getById(change.getTenderId());
		tender.setChanges("Y");
		tenderDao.update(tender);
//		// 转让标的利息
//		BorrowPaymentDetail detail = new BorrowPaymentDetail();
//		detail.setUserId(change.getUserId());
//		detail.setBorrowId(change.getBorrowId());
//		Double paymentInterset = borrowPaymentDetailDao.sumNotPaymentInterestByTidAndBorrowId(detail);
//		// 投资用户(转让用户)待换金额
//		UserTender tender = new UserTender();
//		tender.setUserId(change.getUserId());
//		tender.setBorrowId(change.getBorrowId());
//		tender.setId(change.getTenderId());
//		UserTender tenderInfo = tenderDao.getUserTenderInfo(tender);
//
//		tender.setAwaitFund(tenderInfo.getAwaitFund() - change.getMoney());
//		tender.setAwaitInterest(tenderInfo.getAwaitInterest() - paymentInterset);
//		tender.setAwaitTotal(tender.getAwaitFund() + tender.getAwaitInterest());
//		tenderDao.updateTender(tender);
	}
	
	/**
	 * 承接的债权
	 * @param uid  用户id
	 * @return
	 */
	public PageInfo<MyChangeVo> getChangeListByUserId(MyChangeVo vo) {
		
		int count=changeDao.countMychange(vo);
		List<MyChangeVo> listMyChangeVo =  changeDao.getChangeListByUserId(vo);
		
		PageInfo<MyChangeVo> page=new PageInfo<MyChangeVo>(count, vo.getIndex() , vo.getLimit());
		page.setPageList(listMyChangeVo);
		return page;
	}
	
}
